package com.risen.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.risen.bean.AdminLogininfo;
import com.risen.bean.Book;
import com.risen.bean.Category;
import com.risen.bean.User;
import com.risen.form.BookForm;
import com.risen.service.AdminLogininfoService;
import com.risen.service.BookService;
import com.risen.service.CategoryService;
import com.risen.service.UserService;
import com.risen.util.DateUtils;
import com.risen.util.UUIDGenerator;

@Controller
@RequestMapping("/my")
public class AdminBookController {
	@Autowired
	private BookService bookService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private AdminLogininfoService adminLogininfoService;
	
	@RequestMapping(value = "/init")
	public String init() {
		return "mainresource/test/demo.html";
	}
	
	/**
	 * 管理员登陆验证
	 * @return map
	 * @throws Exception 
	 */
	@RequestMapping(value = "/loginAd", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> loginAd(String username, String password,
			String remeberme, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		/*
		 * 1.校验表单数据是否为空，如果为空返回错误信息
		 */
		if(username==null||username.trim().isEmpty()||password==null||password.trim().isEmpty()){
			result.put("errorCode", "-1");
			result.put("errorMsg", "用户名或密码不正确");
			return result;
		}
		/*
		 * 2.如果数据都不为空，根据表单数据查询数据库进行校验
		 */
		Map<String,String> loginMap=new HashMap<String,String>();
		loginMap.put("username", username);
		loginMap.put("password", password);
		User user=userService.doLogin(loginMap);
		/*
		 * 3.判断查询结果是否为空，证明用户名或者密码错误，显示错误信息
		 */
		if(user==null){
			result.put("errorCode", "-1");
			result.put("errorMsg", "用户名或密码不正确");
			return result;
		} else if (!"1".equals(user.getPermission())) {
			result.put("errorCode", "-2");
			result.put("errorMsg", "权限不足");
			return result;
		}
		/*
		 * 4.判断用户是否勾选"保存密码"复选框，如果有，创建cookie
		 */
		if(remeberme != null && "true".equals(remeberme)){
			//创建两个cookie分别存储用户名和密码返回到浏览器
			Cookie cookie1=new Cookie("loginname",user.getLoginname());
			cookie1.setMaxAge(60*60*24*10);
			cookie1.setPath("/");
			response.addCookie(cookie1);
			Cookie cookie2=new Cookie("loginpass", user.getLoginpass());
			cookie2.setMaxAge(60*60*24*10);
			cookie2.setPath("/");
			response.addCookie(cookie2);
		}
		//数据写入session中
		request.getSession().setAttribute("loginname", username);
		result.put("errorCode", "0");
		return result;
	}
	
	/**
	 * 分页查询书籍信息
	 * @param currentPage
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/findAll", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findAll(Integer currentPage, Integer limit, String cid) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = bookService.findAll(cid, currentPage, limit);
			result.put("errorCode", "0");
		} catch (Exception e) {
			result.put("errorCode", "-1");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 返回ZTree所需数据格式
	 * @return
	 */
	@RequestMapping(value = "/findTree", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findTree() {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Category> entityList= categoryService.getTree();
		List<Map<String, Category>> arraylist = new ArrayList<Map<String, Category>>();
		Map<String, List<Map<String, Category>>> res = new HashMap<String, List<Map<String, Category>>>();
		if (entityList != null) {
			for (int i = 0; i < entityList.size(); i++) {
				Map<String, Category> mapData = new HashMap<String, Category>();
				mapData.put("data", entityList.get(i));
				arraylist.add(mapData);
			}
			res.put("rows", arraylist);
			result.put("data", res);
			result.put("msg", "success!");
		}
		else {
			result.put("msg", "fail!");
		}
		return result;
	}
	
	@RequestMapping(value = "/findUser", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findUser(@RequestParam(value = "name", required = false) String loginname,
			@RequestParam(value = "addTime", required = false) String addTime) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			if (loginname != null && !"".equals(loginname)) {
				loginname = URLDecoder.decode(loginname, "UTF-8");
			}
			param.put("loginname", loginname);
			param.put("addTime", addTime);
			result = userService.findUser(param);
			result.put("errorCode", "0");
		} catch (Exception e) {
			result.put("errorCode", "-1");
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping(value = "/editUser", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> editUser(User user) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(userService.updateUserAd(user)) {
			result.put("errorCode", "0");
			result.put("msg", "更新用户成功！");
		} else {
			result.put("errorCode", "-1");
			result.put("msg", "更新用户失败！");
		}
		return result;
	}
	
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUser(User user) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(userService.insertUserAd(user)) {
			result.put("errorCode", "0");
			result.put("msg", "新增用户成功！");
		} else {
			result.put("errorCode", "-1");
			result.put("msg", "新增用户失败！");
		}
		return result;
	}
	
	@RequestMapping(value = "/delUser", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delUser(String uid) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(userService.delUserById(uid)) {
			result.put("errorCode", "0");
			result.put("msg", "删除用户成功！");
		} else {
			result.put("errorCode", "-1");
			result.put("msg", "删除用户失败！");
		}
		return result;
	}
	
	/**
	 * 得到所有分类
	 * @return
	 */
	@RequestMapping(value = "/getCategory", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getCategory() {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Category> data= categoryService.getTree();
		result.put("data", data);
		return result;
	}
	
	/**
	 * 增加书籍
	 * @param request
	 * @param form
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	@RequestMapping(value = "/addBook", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addBook(HttpServletRequest request, BookForm form) throws Exception, IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		//1.处理字段，得到book实体
		Book book = getEntity(form);
		//2.处理文件
		// 获得项目的路径
		if (!form.getImage_w().isEmpty()) {
			ServletContext sc = request.getSession().getServletContext();
			String basePath = sc.getRealPath("/") + "resources" + File.separator + "images" + File.separator + "book-img";
			File files = new File(basePath);
			if (!files.exists() || !files.isDirectory()) {
				files.mkdirs();
			}
			String filePath = basePath + File.separator + form.getImage_w().getOriginalFilename();
			form.getImage_w().transferTo(new File(filePath));
		}
		if(bookService.save(book)) {
			result.put("errorCode", "0");
			result.put("msg", "新增书籍成功！");
		} else {
			result.put("errorCode", "-1");
			result.put("msg", "新增书籍失败！");
		}
		return result;
	}
	
	/**
	 * 编辑书籍
	 * @param request
	 * @param form
	 * @throws Exception
	 * @throws IOException
	 */
	@RequestMapping(value = "/editBook", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> editBook(HttpServletRequest request, BookForm form) throws Exception, IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		//1.处理字段，得到book实体
		Book book = getEntity(form);
		book.setBid(form.getBid());
		//2.处理文件
		// 获得项目的路径
		if (!form.getImage_w().isEmpty()) {
			ServletContext sc = request.getSession().getServletContext();
			String basePath = sc.getRealPath("/") + "resources" + File.separator + "images" + File.separator + "book-img";
			File files = new File(basePath);
			if (!files.exists() || !files.isDirectory()) {
				files.mkdirs();
			}
			String filePath = basePath + File.separator + form.getImage_w().getOriginalFilename();
			form.getImage_w().transferTo(new File(filePath));
		}
		if(bookService.edit(book)) {
			result.put("errorCode", "0");
			result.put("msg", "编辑书籍成功！");
		} else {
			result.put("errorCode", "-1");
			result.put("msg", "编辑书籍失败！");
		}
		return result;
	}
	
	/**
	 * 删除书籍
	 * @param bid
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delProduct", method = RequestMethod.POST)
	public Map<String, Object> delProduct(Integer bid) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (bookService.deleteBook(bid)) {
			result.put("errorCode", "0");
			result.put("msg", "删除书籍成功！");
		} else {
			result.put("errorCode", "0");
			result.put("msg", "删除书籍失败！");
		}
		return result;
	}
	
	/**
	 * 查看图片
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getImage", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		String filePath = request.getParameter("filePath"); // 文件路径
		ServletContext sc = request.getSession().getServletContext();
		String basePath = sc.getRealPath("/") + "resources" + File.separator + "images" + File.separator + "book-img";
		if (filePath != null && !"".equals(filePath)) {
			response.setContentType("image/jpeg");
			response.setCharacterEncoding("UTF-8");
			//防止查看中文图片乱码，前端给filePaht编码，后端进行解码
			filePath = URLDecoder.decode(filePath, "UTF-8");
			FileInputStream in = null; //本地读文件的输入流
			OutputStream out = null; //返回给浏览器的数据流
			try {
				in  = new FileInputStream(basePath + File.separator + filePath);
				out = response.getOutputStream();
				byte[] b = new byte[20 * 1024];
				int i;
				while ((i = in.read(b, 0, b.length)) != -1) {
					out.write(b, 0, i);
					out.flush();
				}
				result.put("msg", "success");
			} finally {
				in.close();
			}
		} else {
			result.put("msg", "failure");
		}
		return result;
	}
	
	public Book getEntity(BookForm form) {
		Book book = new Book();
		int discIndex = form.getDiscount().length() - 1;
		Double discount = Double.valueOf(form.getDiscount().substring(0, discIndex));
		int cidIndex = form.getCid().indexOf(" ");
		Integer cid = Integer.valueOf(form.getCid().substring(0, cidIndex));
		book.setAuthor(form.getAuthor());
		book.setBname(form.getBname());
		book.setPricing(form.getPricing());
		book.setCurrPrice(form.getCurrPrice());
		book.setDiscount(discount);
		book.setCid(cid);
		book.setPress(form.getPress());
		book.setPublicationTime(form.getPublicationTime());
		book.setEdition(form.getEdition());
		book.setImage_w(form.getImage_w().isEmpty() ? "" : form.getImage_w().getOriginalFilename());
		book.setImage_b(form.getImage_w().isEmpty() ? "" : form.getImage_w().getOriginalFilename());
		return book;
	}
	
	/**
	 * 查询管理员登陆记录
	 * @return
	 */
	@RequestMapping(value = "/getAllLogininfo", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getAllLogininfo(String loginname) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			List<AdminLogininfo> entityList = adminLogininfoService.findAll(loginname);
			result.put("data", entityList);
			result.put("errorCode", "0");
			result.put("msg", "查询记录成功！");
		} catch (Exception e) {
			result.put("errorCode", "-1");
			result.put("msg", "查询记录失败！");
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 查询管理员登陆记录
	 * @return
	 */
	@RequestMapping(value = "/insertLogininfo", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> insertLogininfo(String loginname, String customerAddress, String customerIp, String cityId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String uid = userService.findUserByName(loginname);
			String theId = UUIDGenerator.getLong();
			//构建实体
			AdminLogininfo entity = new AdminLogininfo();
			entity.setTheId(theId);
			entity.setUid(uid);                          //用户id
			entity.setLoginContent("登陆成功！");
			entity.setCustomerAddress(customerAddress);  //地址
			entity.setCustomerIp(customerIp);            //ip
			entity.setCityId(cityId);                    //城市id
			entity.setLoginTime(DateUtils.getNowTime()); //登陆时间
			adminLogininfoService.insert(entity);
			result.put("errorCode", "0");
			result.put("msg", "新增记录成功！");
		} catch (Exception e) {
			result.put("errorCode", "-1");
			result.put("msg", "新增记录失败！");
			e.printStackTrace();
		}
		return result;
	}
	
}
